import { useNavigation } from "@react-navigation/native";
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import {
  Dimensions,
  Keyboard,
  Pressable,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import Icon from "react-native-vector-icons/AntDesign";

interface SearchBarViewProps {
  onSearch: (text: string) => void;
}

const SearchBarView = forwardRef<any, SearchBarViewProps>(
  ({ onSearch }, ref) => {
    const navigation = useNavigation();
    const inputRef = useRef(null);
    const [searchText, setSearchText] = useState("");

    useImperativeHandle(ref, () => ({
      updateSearchText(newText: any) {
        setSearchText(newText);
      },
    }));

    useEffect(() => {
      //@ts-ignore
      inputRef.current?.focus();
    }, []);

    return (
      <View style={styles.headerContainer}>
        <Pressable
          onPress={() => {
            navigation.goBack();
          }}
        >
          <Icon
            name="left"
            size={22}
            style={{ marginRight: 10 }}
            color="rgba(0,0,0,0.3)"
          />
        </Pressable>
        <View style={styles.searchBar}>
          <Icon name="search1" size={20} color="rgba(0,0,0,0.3)" />
          <TextInput
            ref={inputRef}
            style={styles.searchInput}
            placeholder="搜索内容/角色"
            placeholderTextColor="rgba(0,0,0,0.2)"
            selectionColor="#3BC859"
            returnKeyType="search"
            onChangeText={setSearchText}
            value={searchText}
            onSubmitEditing={(value) => {
              onSearch(value.nativeEvent.text);
            }}
          />
        </View>

        <Pressable
          onPress={() => {
            onSearch(searchText);
          }}
        >
          <Text style={styles.searchButtonLabel}>搜索</Text>
        </Pressable>
      </View>
    );
  }
);

const styles = StyleSheet.create({
  headerContainer: {
    width: Dimensions.get("window").width - 30,
    height: 44,
    flexDirection: "row",
    justifyContent: "flex-start",
    alignItems: "center",
    //backgroundColor: "red",
  },
  headerText: {
    fontSize: 18,
    fontWeight: "bold",
  },
  searchBar: {
    width: Dimensions.get("window").width - 40 - 40 - 30,
    height: 36,
    borderRadius: 6,
    justifyContent: "flex-start",
    alignItems: "center",
    paddingHorizontal: 10,
    flexDirection: "row",
    borderWidth: 1,
    borderColor: "#3BC859",
  },
  searchInput: {
    color: "black",
    marginLeft: 2,
    marginTop: 0,
    flex: 1,
    fontSize: 14,
    height: 36,
    padding: 0,
    //backgroundColor: "red",
  },
  searchButtonLabel: {
    marginLeft: 15,
    fontSize: 16,
    color: "black",
    fontWeight: "bold",
  },
});

export default SearchBarView;
